# PowerShell script to modify DemandServiceImpl.java with enhanced logging

$file = "C:\Users\lyc\Desktop\spb\src\main\java\com\expert\miniapp\service\impl\DemandServiceImpl.java"
$content = Get-Content $file -Raw -Encoding UTF8

# Define the old code pattern (using regex to handle encoding issues)
$oldPattern = [regex]::Escape("        String content;") + ".*?" + [regex]::Escape("throw new RuntimeException(`"AI")
$oldPattern = "        String content;[\s\S]*?if \(!StringUtils\.hasText\(content\)\) \{[\s\S]*?throw new RuntimeException\(`"[^`"]+`"\);\s+\}"

# Define the new code
$newCode = @"
        String content;
        String responseBody = "";
        try {
            logger.info("=== 开始调用AI匹配接口 ===");
            logger.info("请求URL: {}", aiConfig.getUrl());
            logger.info("请求payload长度: {} 字符", payloadJson.length());

            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString(UTF_8));
            responseBody = response.body();

            logger.info("=== AI响应诊断信息 ===");
            logger.info("HTTP状态码: {}", response.statusCode());
            logger.info("响应body长度: {} 字符", responseBody != null ? responseBody.length() : 0);
            logger.info("响应body前500字符: {}", responseBody != null && responseBody.length() > 0 ?
                responseBody.substring(0, Math.min(500, responseBody.length())) : "空响应");

            if (response.statusCode() < 200 || response.statusCode() >= 300) {
                logger.error("AI接口返回非2xx状态码: {}, 响应body: {}", response.statusCode(), responseBody);
                throw new RuntimeException("AI匹配接口返回非2xx状态: " + response.statusCode());
            }

            var root = objectMapper.readTree(responseBody);
            logger.info("JSON解析成功");

            var choices = root.path("choices");
            logger.info("choices节点是否存在: {}", !choices.isMissingNode());
            logger.info("choices是否为数组: {}", choices.isArray());
            logger.info("choices数组大小: {}", choices.isArray() ? choices.size() : 0);

            if (!choices.isArray() || choices.isEmpty()) {
                logger.error("AI响应中choices字段无效, 完整响应: {}", responseBody);
                throw new RuntimeException("AI匹配未取得推荐请求采用数据");
            }

            content = choices.get(0).path("message").path("content").asText("");
            logger.info("提取到的content长度: {} 字符", content.length());
            logger.info("content前200字符: {}", content.length() > 0 ?
                content.substring(0, Math.min(200, content.length())) : "空内容");

        } catch (Exception e) {
            logger.error("AI匹配调用失败: {}", e.getMessage(), e);
            logger.error("失败时的响应body: {}", responseBody);
            throw new RuntimeException("AI匹配调用失败: " + e.getMessage(), e);
        }

        if (!StringUtils.hasText(content)) {
            logger.error("AI返回的content为空字符串! 完整响应body: {}", responseBody);
            throw new RuntimeException("AI匹配未返回内容");
        }
"@

# Create backup
Copy-Item $file "$file.backup" -Force
Write-Host "已创建备份: $file.backup"

# Try to replace using line-by-line approach
$lines = Get-Content $file -Encoding UTF8
$newLines = New-Object System.Collections.ArrayList

$inReplacementZone = $false
$skipUntilLine = -1

for ($i = 0; $i -lt $lines.Count; $i++) {
    $line = $lines[$i]

    # Detect start of replacement zone (line 165: "String content;")
    if ($i -eq 164 -and $line -match "^\s+String content;") {
        Write-Host "找到替换起始点: line $($i+1)"
        # Add the new code
        $newCode -split "`n" | ForEach-Object { $newLines.Add($_) | Out-Null }
        $inReplacementZone = $true
        $skipUntilLine = 183  # Skip until line 184 (index 183)
        continue
    }

    # Skip lines in replacement zone
    if ($inReplacementZone -and $i -le $skipUntilLine) {
        continue
    }

    # End of replacement zone
    if ($i -eq 184) {
        $inReplacementZone = $false
    }

    # Add normal lines
    $newLines.Add($line) | Out-Null
}

# Write modified content
$newLines | Set-Content $file -Encoding UTF8 -Force
Write-Host "修改完成! 原文件已备份为 $file.backup"
Write-Host "请重启应用以使更改生效"
"@